from __future__ import absolute_import
from os.path import exists
#import os
import logging
#import subprocess as sp

from forest.registry import register_tool
from forest.tools.system.execute import poll, process

logger = logging.getLogger('forest.tools.system.mdadm')

@register_tool('raid.get_mdadmconf')
def get_mdadmconf():
    lines = []
    for isstderror, line in poll(['mdadm', '--examine', '--scan']):
        if isstderror:
            continue

        lines.append(line.strip())
    return '\n'.join(lines)

@register_tool('raid.create_raid')
def create_raid(devicename, level, components, metadata = 'default'):

    args = ['mdadm','-v']

    args.append('--create')
    #args.append('--assume-clean')
    args += ['--force', '--run', '--auto=yes']
    args.append(devicename)
    args.append('--level=%s' % level)
    args.append('--raid-devices=%s' % len(components))
    args.append('--metadata={}'.format(metadata))
    args.append('--name={}'.format(devicename))

    args += ["/dev/{0}".format(c) for c in components]

    for line in poll(args):
        print line

    #output, errors = p.communicate('y\n')

@register_tool('system.mdadm')
def mdadm(dev, level, component_dev, metadata = 'default'):
    ''' Run mdadm. The raid device administration tool.
        Args:

            dev - string - device name (eg md0)
            level - string - raid level (eg 1, 10)
            component_dev - list - a list of devices strings (eg sda, sdb) making up this raid device.
    '''
    # '-e {0}'.format(metadata)
    for d in component_dev:
        assert exists('/dev/%s' % d), "Raid component device %s does not exist" % d

    args = ['mdadm', '-v']
    args.append('--create')

    mdraiddev = '/dev/{0}'.format(dev)
    args.append(mdraiddev)
    args.append('--level={0}'.format(level))
    args.append('--raid-devices={0}'.format(len(component_dev)))

    #args += ['--assume-clean', '--force']
    #args+=['--metadata=0.90']
    args += ["/dev/{0}".format(cdev) for cdev in component_dev]

    p = process(args)

    #time.sleep(4)

    output, errors = p.communicate('y\n')
    print 'OUT', output
